package cn.itsource.org.service.impl;

import cn.itsource.basic.domain.BaseQuery;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private EmployeeMapper employeeMapper;



    @Override
    @Transactional(readOnly = true)
    public Department loadById(Long id) {
        return departmentMapper.loadById(id);
    }

    @Override
    public void save(Department department) {
        department.init();
        departmentMapper.save(department);
    }

    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKeySelective(department);
    }

    @Override
    public void remove(Long id) {
        departmentMapper.remove(id);
    }

    @Override
    public PageList<Department> queryData(BaseQuery query) {
        //1.创建分页对象
        PageHelper.startPage(query.getPage(), query.getPageSize());
        //2.第二步:查询所有
        List<Department> departments = departmentMapper.loadAll(query);
        //3.创建分页对象
        PageInfo<Department> pageInfo = new PageInfo<>(departments);
        //把pageinfo转成list
        List<Department> list = pageInfo.getList();
        list.forEach(department -> {
            department.setManager(employeeMapper.findOne(department.getManagerId()));
            department.setParent(departmentMapper.loadById(department.getParentId()));
        });

        return new PageList(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public List<Department> findTree() {
        List<Department> list = departmentMapper.findAll();
        return TreeUtil.getTree(list);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        departmentMapper.batchDelete(ids);
    }

    @Override
    public List<Department> findAll() {
        return departmentMapper.findAll();
    }
}
